package wechat.start.wechatstart.controller;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import wechat.start.wechatstart.util.SignUtil;
import wechat.start.wechatstart.util.WechatUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by WuJiXian on 2020/12/4 22:10
 */
@Slf4j
@Controller
@RequestMapping("/wechat")
public class WechatController {

    /**
     * 微信接入验证
     * @param req
     * @param resp
     */
    @GetMapping
    public void access(HttpServletRequest req, HttpServletResponse resp) {
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echoStr = req.getParameter("echostr");
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        PrintWriter out = null;
        try {
            out = resp.getWriter();
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>weixin get success....");
                out.print(echoStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null)
                out.close();
        }
    }

    @PostMapping
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, DocumentException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        Map<String, String> requestMap = WechatUtil.parseXml(req.getInputStream());
        log.info("user send info-->" + requestMap.toString());
        String responseXml = WechatUtil.getResponse(requestMap);
        log.info("responseXml-->" + responseXml);
        if (responseXml == null || responseXml.length() < 1)
            responseXml = "success";
        resp.getWriter().println(responseXml);

    }

}
